package com.hemi.rhet.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.hemi.rhet.Constants;
  
public class HttpUtil {   
  
    /**  
     * http访问数据，默认返回的数据为UTF-8编码  
     *   
     * @param url  
     *            url地址  
     * @param method  
     *            提交方式  
     * @return  
     * @throws IOException  
     */  
    public static String getUrl(String url) throws IOException {   
        HttpGet request = new HttpGet(url);   
        HttpClient httpClient = new DefaultHttpClient();   
        
        if(ApplicationContext.getSessionName()!=null ){

        	if(url.indexOf("?")!=-1)
        	{
        		url=url+"&"+ApplicationContext.getJsessionidUrl();
        	}else{
        		url=url+"?"+ApplicationContext.getJsessionidUrl();
        	}
        }
        
        HttpResponse response = httpClient.execute(request);   
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   
            return EntityUtils.toString(response.getEntity());   
        } else {   
            return "";   
        }   
    }   
    
    public static String buildUrl(String url,boolean add_android_and_current_user){
    	if(!add_android_and_current_user)
    	{
    		return (url.startsWith(ApplicationContext.DOMAIN)?"":ApplicationContext.DOMAIN)+OSInfoUtil.trAppNameUrl(url);
    	}else{
    		return buildUrl(url);
    	}
    }
    public static String buildUrl(String url){
    	String history_url = ApplicationContext.DOMAIN+OSInfoUtil.trAppNameUrl(url);
    	if(history_url.indexOf("?")!=-1)
    	{
    		history_url = history_url.substring(0, history_url.indexOf("?"))+"_android"+history_url.substring(history_url.indexOf("?"), history_url.length());
    	}else{
    		history_url=history_url+"_android";
    	}
    	if(ApplicationContext.getData("userId")!=null && history_url.indexOf("&currentUserId=")==-1)
    	{
    		history_url = history_url+(history_url.indexOf("?")==-1?"?":"&")+"currentUserId="+ApplicationContext.getData("userId");
    	}
    	
    	System.out.println("history_url=============="+history_url);
    	return history_url;
    }
  
    /**  
     * post提交数据  
     *   
     * @param url  
     *            提交地址  
     * @param params  
     *            参数  
     * @return  
     * @throws ClientProtocolException  
     * @throws IOException  
     */  
    public static String postUrl(String url, Map<String, String> params)   
            throws ClientProtocolException, IOException {   
        return postUrl(url, params, "UTF-8");   
    }   
  
    /**  
     * post提交数据  
     *   
     * @param url  
     *            提交地址  
     * @param params  
     *            参数  
     * @param encoding  
     *            参数编码  
     * @return  
     * @throws ClientProtocolException  
     * @throws IOException  
     */  
    public static String postUrl(String url, Map<String, String> params,   
            String encoding) throws ClientProtocolException, IOException {   
        List<NameValuePair> param = new ArrayList<NameValuePair>(); // 参数   
        // param.add(new BasicNameValuePair("par", "request-post"));   
        // //这个参数我不知道是不是非要加这个   
  
        // 添加参数   
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();   
        while (iterator.hasNext()) {   
            Entry<String, String> entry = iterator.next();   
            param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));   
            
        }   
  
        HttpPost request = new HttpPost(url);   
        if(ApplicationContext.getSessionName()!=null ){
        	param.add(new BasicNameValuePair(ApplicationContext.getSessionName(), ApplicationContext.getSessionValue()));   
        	request.setHeader(ApplicationContext.getSessionName(), ApplicationContext.getSessionValue());
        }
        if(ApplicationContext.getData("userId")!=null && params.get("currentUserId")==null && url.indexOf("currentUserId=")==-1 )
        {
        	param.add(new BasicNameValuePair("currentUserId", ApplicationContext.getData("userId").toString()));   
        }
        HttpEntity entity = new UrlEncodedFormEntity(param, encoding);   
        request.setEntity(entity);   
  
        HttpClient client = getHttpClient();   
        
        
        client.getParams().setParameter(   
                CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); // 设置请求超时时间   
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); // 读取超时   
        
        
		 
		
  
        HttpResponse response = client.execute(request);   
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   
        	if(url.endsWith("/login_android"))
            {
            	
            	List<Cookie> cookies = ((AbstractHttpClient) client).getCookieStore().getCookies();  
    			if (!cookies.isEmpty()) {  
    			    for (int g = 0; g < cookies.size(); g++) {  
    			    	Cookie cookie = cookies.get(g);  
    			        if (cookie.getName().equalsIgnoreCase("jsessionid")) {
                            // 使用一个常量来保存这个cookie，用于做session共享之用
    			        		ApplicationContext.setData(Constants._COOKIE_KEY, cookie);
    			        	}
    			    }  
    			}  
            }
            return EntityUtils.toString(response.getEntity());   
        } else {   
            return null;   
        }   
    }   
    
    
    public static HashMap buildJSON2Map (String content) throws JSONException{
    	HashMap mapparams = new HashMap();
    	if(content!=null)
    	{
		 		JSONObject d = new JSONObject(content);
		 		Iterator it = d.keys();
				while(it.hasNext())
				{
					String key  =(String)it.next()+"";
					mapparams.put(key, d.get(key));
				}
    	}
			return mapparams;
    }
    
    public static HashMap postUrl4ResultMap(String url, Map<String, String> params)   
            throws ClientProtocolException, IOException, JSONException {   
        return buildJSON2Map(postUrl(url, params, "UTF-8"));   
    }  
    
    private static AbstractHttpClient httpclient = new DefaultHttpClient();
	public static AbstractHttpClient getHttpClient(){
		return httpclient;
	}
	
  
}  
